import moment from 'moment';
import { onUpdateAnalytic, onInitAnalytic, onNewInitAnalytic } from '@/services/analytics';

const { NODE_ENV } = process.env;

class Analytics {
  constructor() {
    this.lastPage = '';
    this.lastPageDesc = '';
  }
  onInitBrowseId() {
    this.browseId = `${Math.random().toString(16).substr(2, 7)}${moment().valueOf()}`;
    this.lastTime = moment();
    this.isFist = true;
  }
  onStartTimer() {
    if (!this.onCanRequest()) return;
    this.timerInterval = setInterval(() => {
      this.onStart();
    }, 1000 * 40);
  }

  onClearTimer() {
    this.timerInterval && clearInterval(this.timerInterval);
  }

  onInit() {
    try {
      if (!this.onCanRequest()) return;
      if (this.lastPath && !this.lastPage) {
        this.onChangePage(this.lastPath);
      }
      this.onStartTimer();
    } catch (e) {}
  }

  onCanRequest() {
    if (NODE_ENV === 'development') return false;
    if (CLIENT_ENV !== 'release') return false;
    return true;
  }

  onChangePage(path = '', menuItem) {
    this.lastPath = path;
    const { menuCode, menuName } = menuItem ?? {};
    if (!!menuCode && this.lastPage !== menuCode) {
      this.onStart();
      this.lastPage = menuCode;
      this.lastPageDesc = menuName;
      this.onInitBrowseId();
      this.onStart(true);
    }
  }

  onStart(isStart = false) {
    const { lastPage, browseId, lastTime, lastPageDesc } = this;
    if (lastPage.length > 0) {
      if (!isStart && moment().diff(lastTime, 'second') < 5) return;
      this.onBrowseEvent({
        menucode: lastPage,
        time: lastTime.valueOf(),
        uuid: browseId,
        desc: lastPageDesc,
      });
    }
  }

  onBrowseEvent(obj) {
    try {
      if (!this.onCanRequest()) return;
      // 该逻辑昌吉国投环境注销
      // if (this.isFist) {
      //   onInitAnalytic({ ...obj, startTime: obj.time });
      //   if (obj.menucode != 'eamManager') {
      //     onNewInitAnalytic({ ...obj, startTime: obj.time });
      //   }
      // } else {
      //   onUpdateAnalytic({ ...obj, endTime: moment().valueOf() });
      // }
      this.isFist = false;
    } catch (e) {}
  }
}

Analytics.getInstance = (function () {
  let instance;
  return function () {
    instance = instance ? instance : new Analytics();
    return instance;
  };
})();

const analytics = Analytics.getInstance();

export default analytics;
